﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Http.WebHost;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.SessionState;
using AutoMapper;
using Sharp.Infrastructure.Crosscutting;
using System.Threading.Tasks;
using System.Web.Helpers;
using log4net.Config;
using Sharp.Infrastructure.IoC;
using Sharp.Portal;

namespace Sharp.WebBooter
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            XmlConfigurator.Configure();
            Task.WaitAll(
                Task.Run(() =>
                {
                    Platform.InitPortal(typeof(MvcApplication).Assembly);
                }),
                Task.Run(() =>
                {
                    BundleConfig.RegisterBundles(BundleTable.Bundles);
                })
            );

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }

        protected void Application_Error()
        {
            Exception ex = Server.GetLastError().GetBaseException();
            LogHelper.Error(ex);
        }

        protected void Application_PostAuthorizeRequest()
        {
            // WebApi SessionState
            var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
            if (routeData != null && routeData.RouteHandler is HttpControllerRouteHandler)
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }
}
